﻿using System;
using System.Globalization;
using System.Text.RegularExpressions;

namespace CodeSnippet.Options
{
    /// <summary>
    /// Validate the input data against a Regular Expression.
    /// </summary>
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
    public sealed class PatternRuleAttribute : RuleBaseAttribute
    {
        #region Properties
        /// <summary>
        /// Gets the pattern.
        /// </summary>
        /// <value>The pattern.</value>
        public string Pattern { get; private set; }
        #endregion Properties

        #region Initialization
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="pattern"></param>
        public PatternRuleAttribute(string pattern)
        {
            Pattern = pattern;
        }
        #endregion Initialization

        #region Overrides
        /// <summary>
        /// Validate the input data.
        /// </summary>
        /// <param name="value"></param>
        /// <returns><c>true</c> if the given <c>value</c> is valid; otherwise, <c>false</c>.</returns>
        public override bool IsValid(object value)
        {
            // Assume the given data object is not valid.
            var valid = false;

            // Clear any error message.
            ErrorMessage = string.Empty;

            // If so, cast it.
            var data = value as string;
            // Determine if the data object is a string.
            if (data != null)
            {
                // Ensure we have a valid pattern.
                if (Pattern != null)
                {
                    // Evaluate the pattern.
                    valid = Regex.IsMatch(data, Pattern);
                }
            }

            // Determine if the check failed.
            if (!valid)
            {
                // Prepare a message to be displayed to the end user.
                ErrorMessage = string.Format(CultureInfo.InvariantCulture, "The value you entered: {0} doesn't match the given pattern.", value);
            }

            // Return the result of the operation.
            return valid;
        }
        #endregion Overrides
    }
}